// 创建用户相关的仓库
import { defineStore } from "pinia";
import { reqLogin, reqUserInfo } from '@/api/user/index';
import type { LoginForm, User } from "@/api/user/type";
import { ref } from "vue";
import { SET_TOKEN, GET_TOKEN, SET_USER_INFO, GET_USER_INFO, RESET } from '@/utils/localStorage'
//引入路由(常量路由)
import { constRoutes, asnycRoutes, anyRoutes } from '@/router/routes'
import router from "@/router";
// 引入深拷贝
// @ts-ignore
import cloneDeep from 'lodash/cloneDeep'

const useUserStore = defineStore('User', () => {

    const token = ref(GET_TOKEN());
    const asnycMenuRoutes = ref<any[]>([]);
    const userInfo = ref(GET_USER_INFO());


    // 用户登录
    async function userLogin(data: LoginForm) {
        const result = await reqLogin(data);
        if (result.code == 200) {
            token.value = result.data;
            SET_TOKEN(result.data);
            return result.data;
        } else {
            return Promise.reject(new Error(result.message));
        }
    }

    async function checkUserInfo() {
        const result = await reqUserInfo();
        if (result.code === 200) {
            userInfo.value = result.data;
            SET_USER_INFO(result.data);
            updateMenuRoutes();
            return result.data;
        } else {
            return Promise.reject(new Error(result.message));
        }
    }

    async function updateMenuRoutes() {
        if (!userInfo.value) {
            console.log("🚀 ~ updateMenuRoutes ~ userInfo is null")
            await checkUserInfo();
        }
        // 动态路由
        asnycMenuRoutes.value = filterAsyncRoutes((userInfo.value as User).routes, cloneDeep(asnycRoutes));
        asnycMenuRoutes.value.forEach((item: any) => {
            router.addRoute(item)
        })
    }

    function filterAsyncRoutes(routes: string[], asnycRouteList: any[]): any[] {
        return asnycRouteList.filter((item: any) => {
            if (routes.includes(item.name)) {
                if (item.children && item.children.length > 0) {
                    item.children = filterAsyncRoutes(routes, item.children)
                }
                return true;
            }
        })
    }

    function getMenuRoutes() {
        return [...constRoutes, ...anyRoutes].concat(asnycMenuRoutes.value);
    }

    function logout() {
        RESET();
        token.value = null;
        userInfo.value = null;
        asnycMenuRoutes.value.forEach((item: any) => {
            router.removeRoute(item.name)
        })
        asnycMenuRoutes.value = [];
    }

    function setUserInfo(data: User) {
        userInfo.value = data;
        SET_USER_INFO(data);
    }

    function isLogin() {
        return token.value !== null && token.value !== undefined && token.value !== ''
    }

    return {
        userLogin,
        token,
        userInfo,
        getMenuRoutes,
        setUserInfo,
        logout,
        checkUserInfo,
        isLogin,
        updateMenuRoutes

    }
})

export default useUserStore